from PyQt4 import QtCore , QtGui
from lib.customUI import customUI
from lib.papyDB import papyDB , tableInfo
from lib.papyDBTable import *
from taskViewer_UI import taskViewer_UI
from lib.itemModel import Task
from lib import globalVar as GV
import os
try :
    import maya.cmds as cmds
    import sys
    sys.path.append('C:\Python26\Lib\site-packages')
    sys.path.append('D:\kali\General\papyrus\py')
    import MySQLdb
    MAYA = 1
except :
    MAYA = 0



g_taskName , g_taskStatus , g_taskStartD , g_taskFinalD , g_taskEndD , g_taskDesc = range(6)



class insertTaskTableModel(QtCore.QAbstractTableModel):
    def __init__( self ):
        super(insertTaskTableModel, self).__init__()
        self.tasks = []
        self.dirty = False
        
    def headerData( self , section , orientation , role=QtCore.Qt.DisplayRole ):
        if role == QtCore.Qt.TextAlignmentRole:
            if orientation == QtCore.Qt.Horizontal:
                return QtCore.QVariant(int(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter))
            return QtCore.QVariant(int(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter))
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if orientation == QtCore.Qt.Horizontal:
            if section == g_taskName :
                return QtCore.QVariant("Name")
            elif section == g_taskStatus : 
                return QtCore.QVariant("Status")
            elif section == g_taskStartD : 
                return QtCore.QVariant("Start Date")
            elif section == g_taskFinalD : 
                return QtCore.QVariant("Final Date")
            elif section == g_taskEndD : 
                return QtCore.QVariant("End Date")
            elif section == g_taskDesc : 
                return QtCore.QVariant("Description")            
        return QtCore.QVariant(int(section + 1))    
    
    def rowCount( self , index=QtCore.QModelIndex() ):
        return len( self.tasks )
    
    def columnCount( self , index=QtCore.QModelIndex() ):
        return 6
    
    def removeRows( self , position , rows=1 , index=QtCore.QModelIndex() ):
        self.beginRemoveRows(QtCore.QModelIndex(), position, position + rows - 1)        
        self.tasks = self.tasks[:position] + self.tasks[position + rows:]            
        self.endRemoveRows()   
        self.dirty = True     
        return True    
         
    def data( self , index , role=QtCore.Qt.DisplayRole ):
        if (not index.isValid() or not (0 <= index.row() < len(self.tasks))):
            return QtCore.QVariant()   
        iTASK = self.tasks[ index.row() ]
        column = index.column()        
        if role == QtCore.Qt.DisplayRole:
            if column == g_taskName:
                return QtCore.QVariant(iTASK.assetID)
            elif column == g_taskStatus:
                return QtCore.QVariant(iTASK.status)
            elif column == g_taskStartD:
                return QtCore.QVariant(iTASK.startDate)
            elif column == g_taskFinalD:
                return QtCore.QVariant(iTASK.finalDate)            
            elif column == g_taskEndD:
                return QtCore.QVariant(iTASK.endDate)
            elif column == g_taskDesc:
                return QtCore.QVariant(iTASK.description)
        return QtCore.QVariant()
    


class insertItemDiag( taskViewer_UI  ): 
    def __init__( self ,  parent=None ):
        taskViewer_UI.__init__( self , parent )
    
    def setcbIndex( self , pssd ):
        self.iprj , self.iseq , self.ishot = pssd[0][1] , pssd[1][1] , pssd[2][1]
        
    def showDiag( self ):
        if GV.testUserID == '': self.userID = USER_INFO.search('userID' , userLogInName = os.environ['username'])
        else :                  self.userID = GV.testUserID
        self.deptID = USER_INFO.search('deptID' , userID = self.userID)
#        print "user", self.userID
        
        self.setUI()
        self.initPrj()
        self.prj_cb.currentIndexChanged.connect( self.initSeqM )
        self.seq_cb.currentIndexChanged.connect( self.initShotG )   
        self.insertTaskTableModel = insertTaskTableModel()        
        self.task_table.setModel( self.insertTaskTableModel )
        self.search_btn.clicked.connect( self.initialModel )
        self.initSeqM()
        self.initShotG()       
        self.show()
        
#        iprj = [ str( self.prj_cb.itemText(x) ) for x in range( len( self.prj_cb ) ) ].index(self.iprj) if self.iprj != '' else 0
#        self.prj_cb.setCurrentIndex(iprj)   
#        iseq = [ self.seq_cb.itemText(x) for x in range( self.seq_cb.count() ) ].index(self.iseq) if self.iseq != '' else 0
#        self.seq_cb.setCurrentIndex(iseq)
#        ishot = [ self.shot_cb.itemText(x) for x in range( self.shot_cb.count() ) ].index(self.ishot) if self.ishot != '' else 0
#        self.shot_cb.setCurrentIndex(ishot)        
        
        if self.deptID != 2 and self.deptID != 4 and self.deptID != 5 :
            self.shot_cb.setCurrentIndex(0)

        self.initialModel()



    def initialModel( self ):
        if self.deptID not in [2,4,5] :
            self.shot_cb.setCurrentIndex(0)
            
        self.task_table.setColumnWidth( 0 , 70 )
        self.task_table.setColumnWidth( 1 , 45 )
        self.task_table.setColumnWidth( 2 , 78 )
        self.task_table.setColumnWidth( 3 , 78 )
        self.task_table.setColumnWidth( 4 , 78 )
        self.task_table.setColumnWidth( 5 , 250 )
             
        if self.insertTaskTableModel.rowCount() > 0:   
            for x in range( self.insertTaskTableModel.rowCount() ):    
                self.insertTaskTableModel.removeRows( 0 ) 
        for x in self.generateModelList():
            self.insertTaskTableModel.tasks.append( x )
        self.insertTaskTableModel.reset()


    
    def refreshAssetTable( self ):
        if self.deptID in [2, 4, 5] :
            self.searchTask()
        else :
            self.searchTask2()
    
    
    
    def searchTask( self ):
        prj = str( self.prj_cb.currentText() )
        seq = str( self.seq_cb.currentText() )
        shot = str( self.shot_cb.currentText() )
        
        if prj != "--All--" :
            hasASSET = []
            prjID = papyDB.getID("PROJECT", "prjID", "prjCodeName", prj)
            for x in range( papyDB.getFetch("select count(*) from PROJECT_has_ASSET where prjID = '%s'" % prjID)[0][0] ) :
                hasASSET.append( papyDB.getFetch('select assetID from PROJECT_has_ASSET where prjID = "%s"' % prjID)[x][0] )                 
            if seq != "--Master--" :
                hasASSET = []
                seqID = papyDB.getID("SEQUENCES", "seqID", "seqName", seq)
                for x in range( papyDB.getFetch("select count(*) from SEQUENCES_has_ASSET where seqID = '%s'" % seqID)[0][0] ) :
                    hasASSET.append( papyDB.getFetch('select assetID from SEQUENCES_has_ASSET where seqID = "%s"' % seqID)[x][0] )                       
                if shot != "--Global--" :
                    hasASSET = []
                    shotID = papyDB.getID("SHOT", "shotID", "shotName", shot)                    
                    for x in range( papyDB.getFetch("select count(*) from SHOT_has_ASSET where shotID = '%s'" % shotID)[0][0] ) :
                        hasASSET.append( papyDB.getFetch('select assetID from SHOT_has_ASSET where shotID = "%s"' % shotID)[x][0] )
        taskID = []         
        for x in range(len(hasASSET)) : 
            query = "select ID from ASSET_JOB where assetID = '%s' and userID = '%s'" % (hasASSET[x] , self.userID)
            Qlen = papyDB.getFetch("select count(*) from ASSET_JOB where assetID = '%s' and userID = '%s'" % (hasASSET[x] , self.userID))[0][0]
            if Qlen != 1 and Qlen != 0 :
                endID = papyDB.getFetch("select count(*) from ASSET_JOB where assetID = '%s' and userID = '%s'" % (hasASSET[x] , self.userID))[0][0]
                taskID.append( papyDB.getFetch(query)[endID-1][0] ) 
            elif Qlen == 0:
                pass
            else :                    
#                print papyDB.getFetch( query )
                taskID.append( papyDB.getFetch( query )[0][0] )      

        fQuery = "select assetID , status , startDate , finalDate , endDate , description from ASSET_JOB where "
        for x in range(len(taskID)) :
            fQuery += "ID = '%s' or " % taskID[x]
        if taskID == [] :
            fQuery += "ID=0000"
        result = papyDB.getFetch(fQuery[:-3])
        return result
    
    def searchTask2( self ):
        prj = str( self.prj_cb.currentText() )
        seq = str( self.seq_cb.currentText() )    
            
        if prj != "--All--" :
            hasSHOT = []
            prjID = papyDB.getID("PROJECT", "prjID", "prjCodeName", prj)
            for x in range( papyDB.getFetch("select count(*) from SEQUENCES where prjID = '%s'" % prjID)[0][0] ) :
                hasSHOT.append( papyDB.getFetch('select seqID from SEQUENCES where prjID = "%s"' % prjID)[x][0] )                   
            if seq != "--Master--" :
                hasSHOT = []
                seqID = papyDB.getID("SEQUENCES", "seqID", "seqName", seq)
                for x in range( papyDB.getFetch("select count(*) from SHOT where seqID = '%s'" % seqID)[0][0] ) :
                    hasSHOT.append( papyDB.getFetch('select shotID from SHOT where seqID = "%s"' % seqID)[x][0] )     
        
        taskID = []         
        for x in range(len(hasSHOT)) : 
            query = "select ID from JOB_INFO where shotID = '%s' and userID = '%s'" % (hasSHOT[x] , self.userID)
            Qlen = papyDB.getFetch("select count(*) from JOB_INFO where shotID = '%s' and userID = '%s'" % (hasSHOT[x] , self.userID))[0][0]
            if Qlen != 1 and Qlen != 0 :
                endID = papyDB.getFetch("select count(*) from JOB_INFO where shotID = '%s' and userID = '%s'" % (hasSHOT[x] , self.userID))[0][0]
                taskID.append( papyDB.getFetch(query)[endID-1][0] ) 
            elif Qlen == 0:
                pass
            else :                    
#                print papyDB.getFetch( query )
                taskID.append( papyDB.getFetch( query )[0][0] )  
        
        
            
        fQuery = "select shotID , status , startDate , finalDate , endDate , description from JOB_INFO where "
        for x in range(len(taskID)) :
            fQuery += "ID = '%s' or " % taskID[x]
        if taskID == [] :
            fQuery += "ID=0000"
        result = papyDB.getFetch(fQuery[:-3])
#        print "result" , result
        return result

            
    def generateModelList( self ):
        if self.deptID in [2, 4, 5] :
            for assetID , status , startDate , finalDate , endDate , description in self.searchTask() :
                yield Task ( assetID , status , startDate , finalDate , endDate , description )
        else : 
            for shotID , status , startDate , finalDate , endDate , description in self.searchTask2() :
                yield Task ( shotID , status , startDate , finalDate , endDate , description )



    def initSeqM( self ):
        self.initSeq('--Master--')
        
    def initShotG( self ):
        self.initShot('--Global--')



            
if __name__ == '__main__':
    import sys    
    app = QtGui.QApplication(sys.argv)     
    ui = insertItemDiag()
    ui.setcbIndex([[1, 'Phantom'], [1, 'first'], [1, 'sh202'], [0, '']])
    ui.showDiag()   
    app.exec_()           